iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 13
1
自我挑戰組

Ruby菜鳥村村民遊記系列 第 13

遊記ep.13 關聯性的Rails村-3

  • 分享至 

  • xImage
  •  

昨天因為身體不適,半夜還發燒了 Orz
寫文章的時候其實真的沒什麼太多思考,頭一直很痛
也不知道是哪裡來的堅持,還是想把文章寫完才去休息。
也請各位同好、大大們,顧好身體比較實在~

今天繼續來補上前兩天的多對多的關聯性:
前面有介紹到,一台鋼彈可以裝備多項武器
所以多對多的關聯性我們可以這樣想像,
每台鋼彈可以裝備多項武器,每項武器可以被裝備在多台鋼彈上,
這樣我們就可以推敲出,Gundam 跟 Weapon 應該是屬於互相 has_many 的關係,
基本角色到齊了,但我們還需要一個小幫手,Model WeaponLog
WeaponLog 主要是要來幫我們記載 Gundam 及 Weapon 的資訊,
所以我們就先來建置吧!

rails g model WeaponLog gundam:references weapon:references

還記得 references 幫我們做了什麼事嗎?
除了幫我們建置了 gundam_id 以及 weapon_id

class WeaponLog < ApplicationRecord
  belongs_to :gundam
  belongs_to :weapon
end

另外也幫我們寫好了這兩行,接下來我們還得去另外兩個 model 做做手腳~

class Weapon < ApplicationRecord
  has_many :weapon_logs
  has_many :gundams , through: :weapon_logs
end

class Gundam < ApplicationRecord
  belongs_to :pilot
  has_many :weapon_logs 
  has_many :weapons ,through: :weapon_logs
end

別忘了 rails db:migrate !

因為 WeaponLog 也同時擁有了兩者多筆的紀錄,所以同時 belongs_to weapon 以及 gundam
所以也同時 has_many weapon_logs ,
剛剛前面說了,Weapon 及 Gundam 是互相 has_many 的關係,
但後面好像多了什麼? through 是的,我們需要透過 weapon_logs 來讓 weapon 及 gundam 找到彼此,
所以還必須在後面多加一段~

回過頭來,我們可以來試一下
將 w1,w2 裝在 g1上以及 將 w1,w2,w3 裝在 g2上

WeaponLog.all
  WeaponLog Load (0.3ms)  SELECT "weapon_logs".* FROM "weapon_logs"
+----+-----------+-----------+------------------------+------------------------+
| id | gundam_id | weapon_id | created_at             | updated_at             |
+----+-----------+-----------+------------------------+------------------------+
| 1  | 1         | 1         | 2019-09-28 14:09:11... | 2019-09-28 14:09:11... |
| 2  | 1         | 2         | 2019-09-28 14:09:11... | 2019-09-28 14:09:11... |
| 3  | 2         | 1         | 2019-09-28 14:09:27... | 2019-09-28 14:09:27... |
| 4  | 2         | 2         | 2019-09-28 14:09:27... | 2019-09-28 14:09:27... |
| 5  | 2         | 3         | 2019-09-28 14:09:27... | 2019-09-28 14:09:27... |
+----+-----------+-----------+------------------------+------------------------+
5 rows in set

搜尋 weapon_logs 後可以發現
滿足了所謂的多對多條件,
那我們今天就順利地達成任務囉!


上一篇
遊記ep.12 外傳的Git村
下一篇
遊記ep.14 守護者見參!Strong Parameters in Rails村
系列文
Ruby菜鳥村村民遊記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言